/**
 ******************************************************************************
 * @file	apd.c
 * @brief	libotdr-peripheral.so
 *
 * Copyright (C) 2017 桂林聚联科技有限公司, Inc. All Rights Reserved.
 *
 * @section Depend
 *	-# spi_mxs.ko
 *	-# spidev.ko
 *	-# libfpga-2016.so
 *
 * 2016-10-21,MenglongWu,MenglongWoo@aliyun.com
 */
#include <stdio.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>

#include "proginfo.h"
#include "otdr-peripheral.h"

#define DEVICE_DEF_NAME "/dev/mxs-adc"
#define DEF_APD_CH      16

//#if CONFIG_GLINK_TR700_BOARD
#if CONFIG_PROTOCAL_TR700_SPI
#include "fpga-tr700.h"

#define DEF_SPI "/dev/spidev3.0"
static char *device_fpga = DEF_SPI;
#endif

static char *device = DEVICE_DEF_NAME;
static int   apd_ch = DEF_APD_CH;

static void __attribute__((constructor)) _load_apd_env()
{
    char *env = NULL;

    env = getenv("DEVICE_APD_TEMP");
    if (env) {
	device = env;
    }
    env = getenv("DEVICE_ADC_CH");
    if (env) {
	apd_ch = atoi(env) + 20;
    }

    // 读取第一次的垃圾数据
    // int unuse;
    // getTemperature(&unuse);
}

static int _adc_to_temp(int adc)
{
    // TODO ADC 值与温度的对应关系
    float vol  = (adc * 1.85) / 4096.0;
    float dat  = vol - 0.750;
    float temp = dat / 0.010 + 25;

    return (int)(temp * 1000);
}
/**
 * @brief	获取APD温度。
OTDR测试模块需要使用该接口获取APD的温度调整APD电压。
 * @param	null
 * @retval	null
 * @remarks
 * @see
 */

int imx287_fpga_getTemperature(int *data)
{
    int              iRes;
    int              fd;
    int              ret;
    struct fpga_dev *dev;
    int              temp;

    ret = fpga_open(device_fpga, &dev, 5000000);
    switch (ret) {
    case 0:
	// printf("open device success!\n");
	break;
    case -1:
	printf("bus error\n");
	return -1;
    case -2:
	printf("unknow device ID\n");
	return -1;
    }
    fpga_otdr_temp(dev, &temp);
    fpga_close(dev);
    *data = temp;
    return 0;
}

int imx287_arm_getTemperature(int *data)
{
    int iRes;
    int fd;
    fd = open(device, O_RDONLY);

    if (fd < 0) {
	printf("%s() %d:fail open device %s\n", __FUNCTION__, __LINE__, device);
	perror("");
	return -1;
    }
    ioctl(fd, apd_ch, &iRes);
    close(fd);
    *data = _adc_to_temp(iRes);
    return 0;
}

int imx287_get_temp_vol(float *data)
{
    int iRes;
    int fd;
    fd = open(device, O_RDONLY);
    if (fd < 0) {
	printf("%s() %d:fail open device %s\n", __FUNCTION__, __LINE__, device);
	perror("");
	return -1;
    }
    ioctl(fd, apd_ch, &iRes);
    close(fd);
    *data = (iRes * 1.85) / 4096.0;
    // *data = iRes;
    return 0;
}

#ifdef CONFIG_TEMP_FROM_FPGA
PROG_INFO(config, "CONFIG_TEMP_FROM_FPGA=Y");
#endif
#ifdef CONFIG_TEMP_FROM_ARM
PROG_INFO(config, "CONFIG_TEMP_FROM_ARM=Y");
#endif


#ifdef CONFIG_DS2782
PROG_INFO(config, "CONFIG_DS2782=Y");
#else
PROG_INFO(config, "CONFIG_DS2782=N");
#endif
